<template>
    <div class="bi-select-option" :class="optionClass" @click="checkHandler($event)">
        <span v-if="!$slots.default">
            <bi-icon :data="icon"  v-if="icon" ></bi-icon>
            {{label}}
        </span>
        <slot></slot>
    </div>
</template>

<script>
export default {
    inject:['addOption','updateOption','deleteOption','disabled','multiple'],
    props:{
        value:{
            type:[String,Number],
            default:''
        },
        label:{
            type:String,
            default:''
        },
        icon:{
            type:String,
            default:''
        },
    },
    computed:{
        optionClass(){
            let classList = [];
            if(this.disabled){
                classList.push('disabled');
            }

            if(this.check){
                classList.push('checked');
            }

            return classList;
        }
    },
    data(){
        
        let id = 'option'+ Math.random().toString(20).substring(2);
        
        return {
            id,
            check:false
        }
    },
    methods:{
        checkHandler(e){

            if (this.multiple){
                e.stopPropagation();
                this.check =!this.check;
            }else{
                this.check = true;
            }

            if(this.disabled){
                return;
            }
            
            this.updateOption(this.id,this.check);
        }
    },
    mounted(){
       this.addOption(this.id,this.value,this.label,(check)=>{
        
           this.check = check;   
       }); 
    },
    beforeUnmount(){
        this.deleteOption(this.id);
    }
}
</script>